<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg">
        <i class="iconfont metro-lineRoute"></i> 地铁线路
      </div>
      <div class="item-wrapper">
        <div
          class="item"
          v-for="(item, index) in subLineData"
          :key="item.id"
          @click.stop="handleItemClick(item.id)"
        >
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: curId === item.id ? item.color : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: curId === item.id ? '#fff' : '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 站点列表 -->
    <div id="station-controller">
      <div class="title-bg"><i class="iconfont metro-ditie"></i> 地铁站点</div>
      <div class="item-wrapper" >
        <div class="item" :key="index" v-for="(item, index) in stationNames" @click="toStation(item.name)">
          <div
            class="box"
            :style="{
              backgroundColor: selectedStation === item.name ? '#fff' : (item.passed ? '#fff' : 'rgba(0,0,0,0)'),
            }"
          ></div>
          <span :style="{ color: selectedStation === item.name ? '#fff' : '#34c5cf' }">
            {{ item.name }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>




<script setup>
import { ref, onMounted } from 'vue'
import { useLineData } from '@/store'
import HtmlMarker from '../../components/Popup/popup'
import * as Cesium from "cesium";
import {
  getSiteTime,
  spaceDistance,
  getSampleData,
} from "../../cesiumTools/roamTools";
//获取地铁线路数据
const subLineData = ref([])
const stationNames = ref([])

let viewer;
// 创建popup实例
// const popup = new HtmlMarker(viewer, {
//   offset: [0, 0] // 根据需要调整偏移量
// })
let popup
let viewerEntities;

//点击实现站点显示
const stationDatas = ref([]);
const curId = ref(null); // 初始化显示为 null
let lastCurId = null; // 新增：用于存储上一次点击的 id
const positions = ref([]);
const selectedStation = ref(null); // 新增：用于存储当前选中的站点名称

const handleItemClick = (id) => {
    // 获取点击的 id + 轨道数据
  curId.value = id;
  // console.log("点击的 id", id)
  let data = subLineData.value.filter((item) => item.id == id);
  console.log(data,'data')
  // 轨道数据 -- 轨道站点 + 站点名称
  stationDatas.value = data[0];
  stationNames.value = data[0].stationsList.map((item) => {
    let obj = {
      name: item.name,
      passed: false,
    };
    return obj;
  });
  console.log(stationNames.value, "站点的数组");

  // 加载轨道的笛卡尔坐标
  positions.value = [];
  data[0].paths.forEach((item) => {
    positions.value.push(Cesium.Cartesian3.fromDegrees(...Object.values(item)));
  });

  // 触发运行地铁
  toBegin();
}

//开始运行轨道函数
let entity;
const toBegin = () => {
  // 清空实体
  if (entity) {
    viewer.entities.remove(entity);
    entity = null;
  }

  // 计算轨迹运行 总时间 + 轨迹点时间戳
  let timeObj = getSiteTime(positions.value, 150);

  // 开始的时间 -- 年/月/日
  const start = Cesium.JulianDate.fromDate(new Date(2024, 6, 26, 16));
  // 停止时间
  const stop = Cesium.JulianDate.addSeconds(
    start,
    timeObj.timeSum, // 运行的总时间
    new Cesium.JulianDate()
  );

  // 设置系统的时间
  viewer.clock.startTime = start.clone();
  viewer.clock.stopTime = stop.clone();
  viewer.clock.currentTime = start.clone(); // 当前时间

  // 获取 地点+时间戳
  const position = getSampleData(positions.value, start, timeObj.siteTime);

  // 添加运行的 火车模型
  entity = viewer.entities.add({
    // 关联时间
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start,
        stop,
      }),
    ]),
    // 加载模型
    model: {
      uri: "/src/assets/model/metro.gltf",
      minimumPixelSize: 30, // 最小尺寸
      scale: 0.2, // 缩放
    },
    id: "running--subway",
    position,
    orientation: new Cesium.VelocityOrientationProperty(position), // 根据位置调整朝向
  });

  // 获取或设置相机当前正在跟踪的Entity实例
  viewer.trackedEntity = entity;

  // 监听时间事件 -- 时间运行就会触发
  viewer.clock.onTick.addEventListener(tickEventHandler);

  // 添加一个检查以确保在火车到达终点后移除事件监听器
  viewer.clock.onTick.addEventListener(() => {
    if (viewer.clock.currentTime.equals(stop)) {
      viewer.clock.onTick.removeEventListener(tickEventHandler);
      if (entity) {
        viewer.entities.remove(entity);
        entity = null;
      }
    }
  });
};



//火车到站点时停车
const tickEventHandler = () => {
  // 循环车的运行距离
  for (let i = 1; i < stationDatas.value.stationsList.length; i++) {
    // 点击的时候 起始点亮起
    // stationNames.value[0].passed = true;

    // 获取当前时间的车的位置 -- 车的中心点的作标
    let curBusPosition = entity.position.getValue(viewer.clock.currentTime);

     // 更新popup的位置
    popup.changePosition(curBusPosition);

    // 生成一个随机数作为 peopleCount
    let peopleCount = Math.floor(Math.random() * 100)+100; // 随机生成 0 到 99 之间的人数
    let peopleData = {
      id: curId.value,
      number:peopleCount
    }

     // 检测 curId 是否改变
     if (curId.value !== lastCurId) {
      // curId 改变了，重新创建 popup 实例并更新内容
      popup.addLabel({ peopleData });
      lastCurId = curId.value; // 更新 lastCurId 的值
    } else {
      // curId 没有改变，更新 popup 的内容
      if (popup.vmInstance) {
        popup.vmInstance.component.props.peopleData = peopleData;
      }
    }

    // 获取小车站点的位置信息
    const stationPosition = Cesium.Cartesian3.fromDegrees(
      ...Object.values(stationDatas.value.stationsList[i].position)
    );

    // 计算小车距离下一站的距离
    let distance = spaceDistance(curBusPosition, stationPosition);

    // 小于一定距离 -- 公交停站
    if (distance < 10) {
      // 暂停时间
      viewer.clock.shouldAnimate = false;
      setTimeout(() => {
        // 1.5s之后 开启时间
        viewer.clock.shouldAnimate = true;
        // 设置到站显示
        stationNames.value[i].passed = true;
      }, 1500);
    }
  }

  // 检查是否到达终点
  if (viewer.clock.currentTime.equals(viewer.clock.stopTime)) {
    viewer.clock.onTick.removeEventListener(tickEventHandler);
    if (entity) {
      viewer.entities.remove(entity);
      entity = null;
    }
  }
};



/* 05.点击跳转到针对应的站点 -- 点一下跳转;点两下返回实时地铁 */
let pickLabel = null;
const toStation = (name) => {
  // 如果反复点击,则返回跟踪
  if (pickLabel && pickLabel.name == name) {
    console.log(pickLabel.name, "选择的站点名称");
    viewer.trackedEntity = entity;
    return;
  }

  // 关闭轨道追踪 + 调整相机位置
  viewer.trackedEntity = null;
  viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);

  // 查询实体,进行跳转
  pickLabel = viewerEntities.find((item) => item.name === name);
  if (!pickLabel) {
    console.error("未找到对应的站点实体:", name);
    return;
  }
  viewer.flyTo(pickLabel, {
    offset: new Cesium.HeadingPitchRange(0, -Cesium.Math.PI_OVER_TWO, 1000),
  });

  // 更新选中的站点名称
  selectedStation.value = name;
};

onMounted(() => {
  subLineData.value = useLineData().lineData;
  viewer = useLineData().viewer;
  popup = new HtmlMarker(viewer, {
    offset: [200,200] // 根据需要调整偏移量
  })
  viewerEntities = viewer.entities.values;
  stationNames.value = subLineData.value[0].stationsList.map((item) => {
    let obj = {
      name: item.name,
      passed: false,
    };
    return obj;
  });
});

</script>



<style scoped>
.center-wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 70px;
  left: 32.5%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
  cursor:pointer;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
  /* 悬浮显示小手 */
 
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 600px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 38%;
  bottom: 70px;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>



